# -*- coding: utf-8 -*-
import os
import md5

from google.appengine.ext import webapp
from google.appengine.ext.webapp import template

import settings
from utils.auth import require_auth
from utils.auth import add_authed_session
from utils.auth import remove_authed_session
from utils.json import return_json_response
from models.account import Account
from models.menu import MenuType
from models.menu import MenuItem
from models.product import Milk

class MainPage(webapp.RequestHandler):
    '''主页index.html入口'''
    def get(self):
        template_values = {'project_name': settings.PROJECT_NAME,
                           'ext_version': settings.EXT_VERSION,
                           'hjp_js_version': settings.HJP_JS_VERSION,
                           'hjp_css_version': settings.HJP_CSS_VERSION,
                           'use_debug': settings.USE_DEBUG
                           }
        path = os.path.join(os.path.dirname(__file__), 'index.html')
        self.response.out.write(template.render(path, template_values))

class Login(webapp.RequestHandler):
    def get(self):
        get_datas = self.request.GET
        username = get_datas['username']
        password = get_datas['password']
        m1 = md5.new()
        m1.update(password)
        query = Account.all()
        query.filter('name = ', username).filter('password = ', unicode(m1.hexdigest()))
        result = query.fetch(1)
        if len(result) > 0:
            add_authed_session()
            return_json_response(self, {'success': True,
                                        'name': username,
                                        'passwordChanged': False})
        else:
            return_json_response(self, {'success': False,
                                        'passwordChanged': True,
                                        'errors': {'reason': u'用户名或密码错误。'}})
            
class Logout(webapp.RequestHandler):
    @require_auth
    def get(self):
        remove_authed_session()
        self.redirect('/')
        
class GetMenu(webapp.RequestHandler):
    @require_auth
    def get(self):
        #example: /menu/sale_mange
        req = self.request
        url = self.request.url
        slug = url[url.find('menu') + 5:url.find('?')]
        
        menu_type = MenuType.gql('WHERE slug = :1', slug).get()
        results = MenuItem.gql('WHERE menu_type = :1 and parent_menuitem = :2', menu_type.key().id(), int(req.GET['id'])).fetch(1000)
        json_list = []
        for el in results:
            json_list.append({'id': el.key().id(),
                              'text': el.name,
                              'leaf': el.leaf,
                              'description': el.description,
                              'iconCls': el.iconCls,
                              'parent_menuitem_id': el.parent_menuitem,
                              'menu_type_id': el.menu_type
                              })
        return_json_response(self, json_list)
        
class GetMilk(webapp.RequestHandler):
    @require_auth
    def get(self):
#        results = Milk.gql('WHERE 1 = 1').fetch(1000)
        results = Milk.all().fetch(1000)
        json_list = []
        for el in results:
            json_list.append({'id': el.key().id(),
                              'breed': el.breed,
                              'brand': el.brand,
                              'stage': el.stage,
                              'wrap': el.wrap,
                              'state': el.state,
                              'price': el.price,
                              'discount': el.discount,
                              'num': el.num})
        return_json_response(self, {'rows': json_list}) 
    
class InitData(webapp.RequestHandler):
    '''用于初始化数据'''
    def get(self):
        if Account.all().get():
            self.redirect('/')
            return
            
        from initdata import (add_users, add_menus, add_milks)
        add_users()
        add_menus()
        add_milks()
        self.response.out.write('ok!')